// components/input-picker/input-picker.js
import get from "lodash.get";
import size from "lodash.size";

Component({
  properties: {
    options: {
      // 原始选项数据
      type: Array,
      value: [],
    },
    placeholder: {
      type: String,
      value: "请输入或选择",
    },
  },

  data: {
    currentValue: "", // 当前显示值
    pickerVisible: false, // 控制 picker 显示
    searchKeyword: "", // 搜索关键词
    filteredOptions: [], // 过滤后的选项
    selectedOption: null, // 当前选中项
  },

  observers: {
    options: function (opts) {
      console.log({ opts })
      this.setData({ filteredOptions: opts });
    },
  },

  methods: {
    // 输入框输入处理
    handleInput(e) {
      this.setData({ currentValue: e.detail.value });
      this.triggerEvent("change", { value: e.detail.value });
    },

    // 显示 Picker
    showPicker() {
      console.log("00000", this.data.options);
      this.setData({
        pickerVisible: true,
        searchKeyword: "",
        // filteredOptions: this.data.options,
      });
    },

    // 关闭 Picker
    closePicker() {
      this.setData({ pickerVisible: false });
    },

    // Picker 确认选择
    onPickerConfirm(e) {
      console.log('confirm: ', e)
      const resultLabel = get(e.detail.label, [0], "");
      const resultValue = get(e.detail.value, [0], "");
      // console.log('options: ', resultLabel, resultValue, this.data.options)
      // const result = this.data.options.find((val) => (val.id = resultValue));
      // console.log({ result })
      this.setData({
        currentValue: resultLabel,
        pickerVisible: false,
      });
      this.triggerEvent("change", {
        value: resultLabel,
        selectedValue: resultValue,
      });
    },
    handleClear() {
      this.setData({
        searchKeyword: "",
        filteredOptions: this.data.options,
      });
    },
    // 搜索过滤
    handleSearch(e) {
      const keyword = e.detail.value.toLowerCase();
      const filtered = this.data.options.filter(
        (item) =>
          item.label.toLowerCase().includes(keyword) ||
          String(item.value).includes(keyword)
      );
      console.log({ filtered })
      this.setData({
        searchKeyword: keyword,
        filteredOptions: filtered,
      });
    },

    // Picker 列变化
    onColumnChange(e) {
      console.log({ picker: e, select: this.data.filteredOptions })
      // this.setData({
      //   selectedOption: this.data.filteredOptions[e.detail.index],
      // });
    },
  },
});
